package com.pmcc.platform.shopping.web;


import com.pmcc.platform.giftGoods.entity.Goods;
import com.pmcc.platform.giftGoods.repository.GoodsRepository;
import com.pmcc.platform.salesman.repository.SalesmanRepository;
import com.pmcc.platform.shop.repository.ShopInfoRepository;
import com.pmcc.platform.shopping.entity.*;
import com.pmcc.platform.shopping.enums.GiftChange;
import com.pmcc.platform.shopping.repository.*;
import com.pmcc.platform.shopping.service.ShoppingService;


import com.pmcc.platform.user.entity.UserInfo;
import com.pmcc.platform.user.repository.UserInfoRepository;
import com.pmcc.utils.AntPage;
import com.pmcc.utils.ApiResultBean;
import com.pmcc.utils.StringUtil;
import com.pmcc.utils.wechat.WechatMiniConfig;
import com.pmcc.utils.wechat.WechatServiceMessageUtils;
import com.pmcc.utils.wechat.XmlUtils;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController()
@RequestMapping("api/v1/shopping")
@Slf4j
public class ShoppingController {

    @Autowired
    ShoppingService shoppingService;

    @Autowired
    GoodsGiftRepository goodsGiftRepository;

    @Autowired
    GoodsRepository goodsRepository;

    @Autowired
    UserInfoRepository userInfoRepository;

    @Autowired
    ShopLiboryRepository shoppingLiboryRepository;

    @Autowired
    ShoppingGiftChangeLogRepository shoppingGiftChangeLogRepository;

    @Autowired
    ShoppingRepository shoppingRepository;

    @Autowired
    ShopInfoRepository shopInfoRepository;

    @Autowired
    SalesmanRepository salesmanRepository;

    @Autowired
    ShoppingApplyRepository shoppingApplyRepository;


    /**
     * 查询所有导购个人信息
     *
     * @return
     */
    @RequestMapping(value = "/queryAllShopping", method = RequestMethod.GET)
    @ResponseBody
    public ApiResultBean queryAllShopping( String name, String phone,AntPage antPage) {
        return shoppingService.queryAllShopping( name, phone,antPage);
    }


    /**
     * 查看单个导购个人信息
     *
     * @return
     */
    @RequestMapping(value = "/queryShopping", method = RequestMethod.GET)
    @ResponseBody
    public ApiResultBean queryShopping(String shoppingId) {
        return shoppingService.querySalesman(shoppingId);
    }


    /**
     * 添加导购
     *
     * @return
     */
    @RequestMapping(value = "/addShopping", method = RequestMethod.POST)
    @ResponseBody
    public ApiResultBean addShopping(Shopping shopping) {
        return shoppingService.addShopping(shopping);
    }

    /**
     * 删除导购
     *
     * @return
     */
    @RequestMapping(value = "/delShopping", method = RequestMethod.POST)
    @ResponseBody
    public ApiResultBean delShopping(String shoppingId) {
        return shoppingService.delShopping(shoppingId);
    }

    /**
     * 修改导购个人信息
     *
     * @param shopping
     * @return
     */
    @RequestMapping(value = "/modifyShopping", method = RequestMethod.POST)
    @ResponseBody
    public ApiResultBean modifyShopping(Shopping shopping) {
        return shoppingService.modifyShopping(shopping);
    }

    /**
     * 导购更换店铺
     *
     * @param shoppingId
     * @param shopId
     * @return
     */
    @RequestMapping(value = "/modifyShoppingChange", method = RequestMethod.POST)
    @ResponseBody
    public ApiResultBean modifyShoppingChange(String shoppingId, String shopId) {
        return shoppingService.modifyShoppingChange(shoppingId, shopId);
    }

    /**
     * 查看导购当前绑定的店铺
     *
     * @param shoppingId
     * @return
     */
    @RequestMapping(value = "/queryShop", method = RequestMethod.GET)
    @ResponseBody
    public ApiResultBean queryShop(String shoppingId) {
        return shoppingService.queryShop(shoppingId);
    }


    /**
     * 查看导购历史门店
     *
     * @param shoppingId
     * @return
     */
    @RequestMapping(value = "/queryHistoryShop", method = RequestMethod.GET)
    @ResponseBody
    public ApiResultBean queryHistoryShop(String shoppingId) {
        return shoppingService.queryHistoryShop(shoppingId);
    }




    /**
     * 领奖接口
     * @param goodGiftId
     * @param longitude
     * @param latitude
     * @return
     */
    @RequestMapping(value = "/getGoodGift", method = RequestMethod.GET)
    @ResponseBody
    public ApiResultBean getGoodGift(String goodGiftId, String longitude, String latitude) {

        return shoppingService.getGoodGift(goodGiftId, longitude, latitude);
    }







    /**
     * 扫加添加好友回调方法
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/wechatAccountsBack")
    @ResponseBody
    @CrossOrigin
    public String wechatAccountsBack(HttpServletRequest request, HttpServletResponse response) {
        log.info("进入微信公众号回调方法--------------start————————————————————");
        String openid = request.getParameter("openid");
        String nonce = request.getParameter("nonce");
        String timestamp = request.getParameter("timestamp");
        String signature = request.getParameter("signature");
        String echostr = request.getParameter("echostr");
        String subscribe = request.getParameter("Event");
        try {
            Map<String, String> map = XmlUtils.xmlToMap(request);
            String fromUserName = map.get("FromUserName");//消息来源用户标识
            String toUserName = map.get("ToUserName");//消息目的用户标识
            String msgType = map.get("MsgType");//消息类型
            String createTime = map.get("CreateTime");//消息内容
            String event = map.get("Event");//消息内容
            String content = map.get("Content");
            String personService = map.get("EventKey");
            String latitude = map.get("Latitude");
            String longitude = map.get("Longitude");


            if (StringUtil.isNotEmpty(personService)) {

                // 用户未关注时，进行关注后的事件推送
                if (event.equals("subscribe")) {

                    String token = WechatMiniConfig.getAccessToken1();
                    List<UserInfo> userInfos = userInfoRepository.findAllByOppenIdAndDelFlag(openid, "0");
                    if (userInfos.size() == 0) {
                        //保存用户oppenid
                        UserInfo userInfo = new UserInfo();
                        userInfo.setOppenId(openid);
                        userInfo.setLongitude(longitude);
                        userInfo.setLatitude(latitude);
                        userInfoRepository.save(userInfo);
                    }
                    String s = shoppingService.getUserUnionId(openid, token);


                    String accessToken = WechatMiniConfig.getAccessToken1();
                    String id = personService.split("_")[1];
                    GoodsGift goodsGift = goodsGiftRepository.findAllByIdAndDelFlag(id, "0");
                    if (goodsGift != null) {
                        String content1 = "";
                        String content2 = "";
                        if (goodsGift.getState().equals("1")) {
                            content1 = "二维码已失效";
                        } else {

                            //保存赠品记录
                            goodsGift.setUserOpenId(openid);
                            goodsGift.setState("1");
                            goodsGift.setGetTime(new Date());
                            goodsGiftRepository.saveAndFlush(goodsGift);
                            Goods goods = goodsRepository.findAllByIdAndDelFlag(goodsGift.getGoodsId(), "0");
                            Shopping shopping=shoppingRepository.findOne(goodsGift.getShoppingId());
                            List<ShopLibory> shoppingLibory = shoppingLiboryRepository.findAllByShopIdAndDelFlag(shopping.getShopId(), "0");
                            if (shoppingLibory.size() > 0) {
                                if (shoppingLibory.get(0).getGoodsNum() > 0) {
                                    content1 = "欢迎您的关注，我是北京超级节点的小优兔，为您提供以下服务:" +
                                            "恭喜你获得" + goods.getName() + goods.getSpecification();
                                    //更新导购赠品库数量
                                    shoppingLibory.get(0).setGoodsNum(shoppingLibory.get(0).getGoodsNum() - 1);
                                    shoppingLiboryRepository.save(shoppingLibory.get(0));

                                    //添加导购赠品更换记录
                                    ShoppingGiftChangeLog shoppingGiftChangeLog = new ShoppingGiftChangeLog();
                                    shoppingGiftChangeLog.setGiftChange(GiftChange.GRANT);

                                    shoppingGiftChangeLog.setChangeNum(1);
                                    shoppingGiftChangeLogRepository.save(shoppingGiftChangeLog);
                                } else {
                                    content1 = "二维码已失效";
                                }


                            }
                        }

                        String s1 = WechatServiceMessageUtils.sendMessageText(openid, content1, accessToken);
                    }


                }
                //用户已关注时的事件推送
                if (event.equals("SCAN")) {
                    String accessToken = WechatMiniConfig.getAccessToken1();
                    List<UserInfo> userInfos = userInfoRepository.findAllByOppenIdAndDelFlag(openid, "0");
                    if (userInfos.size() == 0) {
                        //保存用户oppenid
                        UserInfo userInfo = new UserInfo();
                        userInfo.setOppenId(openid);
                        userInfo.setLongitude(longitude);
                        userInfo.setLatitude(latitude);
                        userInfoRepository.save(userInfo);
                    }
                    String s = shoppingService.getUserUnionId(openid, accessToken);


                    String id = personService;
                    GoodsGift goodsGift = goodsGiftRepository.findAllByIdAndDelFlag(id, "0");
                    if (goodsGift != null) {
                        String content1 = "";
                        if (goodsGift.getState().equals("1")) {
                            content1 = "二维码已被领取";

                        } else {
                            //更新赠品记录
                            goodsGift.setUserOpenId(openid);
                            goodsGift.setState("1");
                            goodsGift.setGetTime(new Date());
                            goodsGiftRepository.save(goodsGift);
                            Goods goods = goodsRepository.findAllByIdAndDelFlag(goodsGift.getGoodsId(), "0");

                            Shopping shopping=shoppingRepository.findOne(goodsGift.getShoppingId());
                            List<ShopLibory> shoppingLibory = shoppingLiboryRepository.findAllByShopIdAndGoodsIdAndDelFlag(shopping.getShopId(),goods.getId(), "0");
                            if (shoppingLibory.size() > 0) {
                                if (shoppingLibory.get(0).getGoodsNum() > 0) {
                                    content1 = "欢迎您的关注，我是北京超级节点的小优兔，为您提供以下服务:" +
                                            "恭喜你获得" + goods.getName() + goods.getSpecification();
                                    //更新导购赠品数量
                                    shoppingLibory.get(0).setGoodsNum(shoppingLibory.get(0).getGoodsNum() - 1);
                                    shoppingLiboryRepository.save(shoppingLibory.get(0));

                                    //更新导购赠品更换记录
                                    ShoppingGiftChangeLog shoppingGiftChangeLog = new ShoppingGiftChangeLog();
                                    shoppingGiftChangeLog.setGiftChange(GiftChange.GRANT);
                                    shoppingGiftChangeLog.setChangeNum(1);

                                    shoppingGiftChangeLogRepository.save(shoppingGiftChangeLog);
                                } else {
                                    content1 = "二维码已失效";
                                }


                            }


                        }
                        String s1 = WechatServiceMessageUtils.sendMessageText(openid, content1, accessToken);
                    }

                }


            }

        } catch (Exception e) {
            System.out.println(e);

        }
        return echostr;
    }




}
